package cn.jetpiece.cloud.joss.app.modular.object.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.jetpiece.cloud.joss.api.object.BucketApi;
import cn.jetpiece.cloud.joss.api.object.model.params.CreateBucketParam;
import cn.jetpiece.cloud.joss.api.object.model.params.UpdateBucketParam;
import cn.jetpiece.cloud.joss.api.object.model.query.BucketQuery;
import cn.jetpiece.cloud.joss.api.object.model.result.BucketResult;
import cn.jetpiece.cloud.joss.app.modular.object.entity.Bucket;
import cn.jetpiece.cloud.joss.app.modular.object.enums.BasicExceptionEnum;
import cn.jetpiece.cloud.joss.app.modular.object.service.BucketService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.jetpiece.cloud.model.contants.ResponseMsgConstants;
import cn.jetpiece.cloud.model.exception.ServiceException;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import org.springframework.web.bind.annotation.RestController;

/**
 * 桶控制器
 *
 * @author XuJZ
 * @since 2020-09-05 15:41:52
 */
@Slf4j
@RestController
@AllArgsConstructor
public class BucketController implements BucketApi {
    private final BucketService bucketService;

    @Override
    public Result<String> add(CreateBucketParam param) {
        if (bucketService.add(param)) {
            return Result.OK(ResponseMsgConstants.CREATE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.CREATE_ERROR);
        }
    }

    @Override
    public Result<String> update(UpdateBucketParam param) {
        if (bucketService.update(param)) {
            return Result.OK(ResponseMsgConstants.UPDATE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.UPDATE_ERROR);
        }
    }

    @Override
    public Result<String> delete(String id) {
        Bucket bean = bucketService.getById(id);
        if (bean == null) {
            throw new ServiceException(BasicExceptionEnum.BUCKET_NOT_EXISTED);
        }
        if (bucketService.delete(id)) {
            return Result.OK(ResponseMsgConstants.DELETE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.DELETE_ERROR);
        }
    }

    @Override
    public Result<BucketResult> get(String id) {
        Bucket bean = bucketService.getById(id);
        if (bean == null) {
            return Result.OK();
        }
        BucketResult result = new BucketResult();
        BeanUtil.copyProperties(bean, result);
        return Result.OK(result);
    }

    @Override
    public Result<PageResult<BucketResult>> page(BucketQuery query) {
        return Result.OK(bucketService.page(query));
    }

}
